#$Id: captcha.py 32816 2008-08-29 08:56:57Z jorwen@NETEASE.COM $

from Captcha.Visual import Text, Backgrounds, Distortions
from Captcha import Words
import random
import Image

class BaseRender(object):
    defaultSize = (100,30)
    defaultfontfactory = Text.FontFactory(20, "vera")
   
    def __init__(self):
        self.fontfactory = None

    def render(self, word=None, size=None):
        if size is None:
            size = self.defaultSize
        if not word:
            word = Words.defaultWordList.pick()
        return word, self.__do_render(self.get_layers(word), Image.new("RGB", size))
   
    def get_layers(self, word):
        return self.renderlist
   
    def set_font_factory(self, factory):
        self.fontfactory = factory
       
    def get_font_factory(self):
        if not self.fontfactory:
            return self.defaultfontfactory
        return self.fontfactory

    def __do_render(self, _list, img):
        for i in _list:
            if isinstance(i, (tuple, list)):
                img = self.__do_render(img)
            else:
                img = i.render(img) or img
        return img
   

class PseudoGimpy(BaseRender):
    def get_layers(self, word):
        return [
            random.choice([Backgrounds.CroppedImage(), Backgrounds.TiledImage(), ]),
            Text.TextLayer(word, borderSize=1, fontFactory=self.get_font_factory()),
            Distortions.SineWarp(),
            ]


class AngryGimpy(BaseRender):
    def get_layers(self, word):
        return [
            Backgrounds.TiledImage(),
            Backgrounds.RandomDots(),
            Text.TextLayer(word, borderSize=1, fontFactory=self.get_font_factory()),
            ]


class AntiSpam(BaseRender):
    fontFactory = Text.FontFactory(20, "vera/VeraBd.ttf")

    def get_layers(self, word):
        textLayer = Text.TextLayer(word, borderSize = 1, fontFactory = self.fontFactory) 
        return [
            Backgrounds.CroppedImage(),
            textLayer,
            Distortions.SineWarp(amplitudeRange = (2, 4)),
            ]

def get_image(word=None, style='angry', size=None):
    StyleDict = {
		'pseudo': PseudoGimpy,
		'angry': AngryGimpy,
		'antispam': AntiSpam}
    cls = StyleDict.get(style, AntiSpam)
    obj = cls()
    word, img = obj.render(word)
    return word, img



if __name__ == '__main__':
    word, img = get_image(style='angry')
    img.save('b.jpg', 'JPEG')
    print word
